package com.yt.phone.service;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.phone.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.phone.mapper.VirtualphoneMapper;
import com.yt.phone.models.service.IVirtualphoneService;
import com.yt.phone.models.bo.VirtualphoneSaveBO;
import com.yt.phone.models.dto.VirtualphoneDTO;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 虚拟电话号码信息控制器
 *
 * @author lizicong
 * @Date 2025-10-27 10:13:37
 */
@DubboService
public class VirtualphoneServiceImpl extends ServiceImpl<VirtualphoneMapper, VirtualphoneDTO> implements IVirtualphoneService {

    @Resource
    private YmlConfig ymlConfig;

    @Resource
    private VirtualphoneMapper virtualphoneMapper;

    @Override
    public boolean add(VirtualphoneSaveBO saveBO) {
        VirtualphoneDTO dto = new VirtualphoneDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setVirtualphoneId(id);
        return this.insert(dto);
    }

    @Override
    public List<VirtualphoneDTO> getvirtualphoneList() {
        List<VirtualphoneDTO> virtualphoneList = virtualphoneMapper.selectList(null);
        return virtualphoneList;
    }

    @Override
    public Page<VirtualphoneDTO> getpagevirtualphoneList(int currentPage) {
        // 1. 校验页码（最小为1）
        if (currentPage < 1) {
            currentPage = 1;
        }
        // 2. 定义每页条数
        int pageSize = 5;
        // 3. 计算分页起始位置
        int offset = (currentPage - 1) * pageSize;
        RowBounds rowBounds = new RowBounds(offset, pageSize);

        EntityWrapper<VirtualphoneDTO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("create_time", false);
        // 4. 获取当前页数据（List类型）
        List<VirtualphoneDTO> records = virtualphoneMapper.selectPage(rowBounds, wrapper);

        // 5. 查询总记录数
        int totalCount = virtualphoneMapper.selectCount(null);

        // 6. 手动封装 Page 对象（无需设置 pages，由 Page 自动计算）
        Page<VirtualphoneDTO> page = new Page<>(currentPage, pageSize);
        page.setRecords(records); // 设置当前页数据
        page.setTotal(totalCount); // 设置总记录数（pages 会自动根据 total 和 size 计算）

        return page;
    }

    @Override
    public List<VirtualphoneDTO> searchgetvirtualphoneList(String keyword) {
        Wrapper<VirtualphoneDTO> wrapper = new EntityWrapper<>();
        wrapper.like("virtualphone_number", keyword)
                .or()
                .like("virtualphone_address", keyword);
        List<VirtualphoneDTO> virtualphoneList = virtualphoneMapper.selectList(wrapper);
        return virtualphoneList;
    }
}
